package UDP;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Arrays;

public class UDPServer {
    public static void main(String[] args) throws IOException {
        // 要发送的信息
        String messg = "这里是肯德基，您的芝士汉堡已经制作完毕，祝您用餐愉快";
        // 建立Socket
        DatagramSocket socket = new DatagramSocket(9999);
        try {
            // 建立收发容器
            byte[] sendData;
            byte[] receiveData = new byte[1024];
            // 接收数据包
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            socket.receive(receivePacket);
            String receivedMessage = new String(receivePacket.getData(), 0, receivePacket.getLength());
            System.out.println("Received from Client: " + receivedMessage);
            // 发送数据包
            sendData = messg.getBytes();
            InetAddress clientAddress = receivePacket.getAddress();
            int clientPort = receivePacket.getPort();
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientAddress, clientPort);
            socket.send(sendPacket);
        } finally {
            // 关闭套接字
            if (socket != null && !socket.isClosed()) {
                socket.close();
            }
        }
    }
}


//import java.io.IOException;
//import java.net.DatagramPacket;
//import java.net.DatagramSocket;
//import java.net.InetAddress;
//import java.net.SocketException;
//import java.util.Arrays;
//
//public class UDP.UDPServer {
//    public static void main(String[] args) throws IOException {
//        //要发送的信息
//        String messg = "This is UDP.UDPServer";
//        //建立Socket
//        DatagramSocket socket = new DatagramSocket(9999);
//        //建立收发容器
//        byte[] sendData;
//        byte[] receiveData = new byte[1024];
//        //接收数据包
//        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
//        socket.receive(receivePacket);
//        String receivedMessage = new String(receivePacket.getData(), 0, receivePacket.getLength());
//        System.out.println("Received from Client: " + receivedMessage);
//        //发送数据包
//        sendData = messg.getBytes();
//        InetAddress clientAddress = receivePacket.getAddress();
//        int clientPort = receivePacket.getPort();
//        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientAddress, clientPort);
//        socket.send(sendPacket);
//        //关闭资源
//        socket.close();
//    }
//}
